import re


def format_level(txt: str, n: int):
    prefix = "----\n" if n == 1 else "\n"
    return prefix + "#" * n + " " + txt


def convert(line: str):
    if line is None:
        return " "

    # Table Of Contents
    if "<<TableOfContents()>>" in line:
        # line = "[TOC]\n"
        line = "\n"

    # Page Title
    if "## page was renamed from" in line:
        # obj = re.search("(## page was renamed from (.*))", line)
        # if obj:
        # line = line.replace(obj.groups()[0], format_level(obj.groups()[1], 1))
        line = "\n"

    # Bold & Italics
    obj = re.search(r"(('{2,3}) *(.+?) *('{2,3}))", line)
    if obj:
        line = line.replace(obj.groups()[0], " **" + obj.groups()[2] + "** ")

    # Image
    imgs = re.findall(r"({{(.*?)}})", line)
    for img in imgs:
        line = line.replace(img[0], "![" + img[1] + "]()")

    # Title
    obj = re.search(r'((={1,5}) (.*?) (={1,5}))', line)
    if obj:
        n = line.count('=') // 2 - 1
        line = line.replace(obj.groups()[0], format_level(obj.groups()[2], n))

    # List
    obj = re.match("(( {1,5})([*\.]) )", line)
    if obj:
        line = line.replace(obj.groups()[0], obj.groups()[1] + '- ')

    # Code Block
    obj = re.search('({{{) *$', line)
    if obj:
        line = line.replace(obj.group(1), "\n```shell")
    obj = re.search('(}}}) *$', line)
    if obj:
        line = line.replace(obj.group(1), "\n```")

    # Link
    links = re.findall('(\[\[(.+?)\]\])', line)
    for link in links:
        line = line.replace(link[0], "[" + link[1] + "](" + link[1] + ")")

    return line


def delete_blank_lines(text):
    return re.sub('\n[\n]+', '\n\n', text)


def main():
    file_name = "wiki.txt"
    with open(file_name, "r") as f:
        lines = f.readlines()

    dst = "----\n"
    for i, line in enumerate(lines):
        # print("%r" % line)
        new_line = convert(line)
        # print("%r" % new_line)
        # print()
        dst = dst + new_line

    dst = delete_blank_lines(dst)

    with open("wiki.md", "w") as f:
        f.write(dst)

    print("Done.")


if __name__ == '__main__':
    main()
